var controllers = {};

controllers.SignInController = function ($scope, $rootScope, $http, $window, $location, AuthService, HfrConfig, HfrStorage, HfrInit) {
	//Init message alert
	HfrInit.message();
	
    // Here we do the authentication processing and error handling.
    // Note that authResult is a JSON object.
    $scope.processAuth = function(authResult) {
        // Do a check if authentication has been successful.
        if(authResult['access_token']) {
            // Successful sign in.
            $scope.signedIn = true;
            if ($rootScope.username === undefined) {
            	$scope.getUserInfo(authResult);
            }
            
        } else if(authResult['error']) {
            // Error while signing in.
            $scope.signedIn = false;
        }
    };
 
    // When callback is received, we need to process authentication.
    $scope.signInCallback = function(authResult) {
        $scope.$apply(function() {
            $scope.processAuth(authResult);
        });
    };
 
    // Render the sign in button.
    $scope.renderSignInButton = function() {
        gapi.signin.render('signInButton',
            {
                'callback': $scope.signInCallback, // Function handling the callback.
                'clientid': HfrConfig.GooglePlus.clientId, // CLIENT_ID from developer console which has been explained earlier.
                'requestvisibleactions': 'http://schemas.google.com/AddActivity', // Visible actions, scope and cookie policy wont be described now,
                                                                                  // as their explanation is available in Google+ API Documentation.
                'scope': 'https://www.googleapis.com/auth/plus.profile.emails.read',
                //'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email',
                'cookiepolicy': 'single_host_origin'
            }
        );
    }
  
    // Request user info.
    $scope.getUserInfo = function(authResult) {
    	//var urlInfo = "https://www.googleapis.com/oauth2/v2/tokeninfo?id_token=" + authResult['id_token'];
    	var urlInfo = HfrConfig.ApiServiceUrl.customersUrlApi + "?id_token=" + authResult['id_token'];
    	$http.get(urlInfo).success(function (data) {
    		if (data.status == 200) {
    			$rootScope.username = data.response.token.email;
    			$rootScope.totalPost = Object.keys(data.response.postSuccess).length;
        		
        		AuthService.create(authResult['id_token'], $rootScope.username);
        		HfrStorage.set("totalPost", $rootScope.totalPost);
        		var dashboard = $location.absUrl().replace("home.html", "");
        		$window.location.href = dashboard;
    		} else {
    			$rootScope.message.error = true;
				$rootScope.message.text = data.message;
    		}
		})
		.error(function(data) {
			$rootScope.message.error = true;
			$rootScope.message.text = "can't connect to server";
		});
    };

    if ($rootScope.isAuthenticated === undefined || !$rootScope.isAuthenticated) {
    	$scope.renderSignInButton();
    }
    
    //Logout
    $scope.logout = function () {
    	$scope.signedIn = false;
    	AuthService.remove();
    	
    	gapi.auth.signOut();
    	$window.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=" + $location.absUrl();
    	return false;
    };
    
};

controllers.HomeController = function ($scope, $rootScope) {

};

hfrApp.controller(controllers);